#pragma once

#include<iostream>
#include<string>
#include<cstdio>
#include<unordered_set>

class Command
{
public:
    Command()
    {
        _white_list.insert("ls");
        _white_list.insert("pwd");
        _white_list.insert("ll");
        _white_list.insert("touch");
        _white_list.insert("who");
        _white_list.insert("whoami");
    }
    bool SafeCheck(std::string& cmdstr)
    {
        //不安全返回0
        auto iter = _white_list.find(cmdstr);
        return iter == _white_list.end() ? false : true;
    }
    std::string Excute(std::string cmdstr)
    {
        if(!SafeCheck(cmdstr))   return "不支持";

        //1pipe
        //2fork + dup2(pipe[1],1) + exec*, 执行结果返回给父进程
        //3 return
        //或者用popen = 1 + 2 + 3
        FILE* fp =  ::popen(cmdstr.c_str(), "r");
        return std::string();
        if(fp == nullptr)
        {
            return "Fail";
        }
        char buffer[1024];
        std::string result;
        while(1)
        {
            char* ret = ::fgets(buffer, sizeof(buffer), fp);
            if(!ret)    break;
            result += ret;
        }
        pclose(fp);
        return result.empty()?std::string("Done") : result;
    }
private:
    std::unordered_set<std::string> _white_list;
};